package com.itheima.leyou.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.leyou.dao.OrderDao;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
public class OrderService {

    @Resource
    OrderDao orderDao;

    @Autowired
    AmqpTemplate amqpTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RestTemplate restTemplate;

    public Map<String, Object> getOrder(String order_id){
        Map<String, Object> resultMap = new HashMap<String, Object>();

        if (order_id==null||order_id.equals("")){
            resultMap.put("result", false);
            resultMap.put("msg", "参数传入有误！");
            return resultMap;
        }

        ArrayList<Map<String, Object>> list = orderDao.getOrder(order_id);
        resultMap.put("master", list);
        resultMap.put("result", true);
        resultMap.put("msg", "");
        return resultMap;
    }


    public Map<String, Object> insertOrder(Map<String, Object> orderInfo){
        Map<String, Object> map = new HashMap<String, Object>();
        if (orderInfo==null||orderInfo.isEmpty()){
            map.put("result", false);
            map.put("msg", "传入参数有误！");
            return map;
        }

        boolean result = orderDao.insertOrder(orderInfo);

        if (!result){
            map.put("result", false);
            map.put("msg", "订单写入失败！");
            return map;
        }

        map.put("result", true);
        map.put("msg", "");
        return map;
    }

    @Transactional
    public Map<String, Object> updateOrderStatus(String order_id, String sku_id){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (order_id==null||order_id.equals("")){
            resultMap.put("result", false);
            resultMap.put("msg", "订单有误！");
            return resultMap;
        }

        boolean result = orderDao.updateOrderStatus(order_id);

        if (!result){
            resultMap.put("result", false);
            resultMap.put("msg", "订单状态更新失败！");
            return resultMap;
        }

        amqpTemplate.convertAndSend("storage_queue", sku_id);

        resultMap.put("result", true);
        resultMap.put("msg", "");
        return resultMap;
    }

    public Map<String, Object> payOrder(String order_id, String sku_id){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (order_id==null||order_id.equals("")){
            resultMap.put("result", false);
            resultMap.put("msg", "订单有误！");
            return resultMap;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order_id", order_id);
        map.put("sku_id", sku_id);
        String json = JSON.toJSONString(map);

        amqpTemplate.convertAndSend("order_status_queue", json);

        resultMap.put("result", true);
        resultMap.put("msg", "");
        return resultMap;
    }


    public Map<String, Object> createOrder(Map<String, Object> orderInfo){
        //orderInfo里的信息是 sku_id，user_id
        Map<String, Object> resultMap = new HashMap<String, Object>();

        //1、判断orderInfo的内容
        if (orderInfo==null||orderInfo.isEmpty()){
            resultMap.put("result", false);
            resultMap.put("msg", "参数有误！");
            return resultMap;
        }

        //2、通过取政策查看商品在不在政策里，key:LIMIT_POLICY_{sku_id}
        String sku_id = orderInfo.get("sku_id").toString();
        String limitPolicy = stringRedisTemplate.opsForValue().get("LIMIT_POLICY_"+sku_id);
        Map<String, Object> policyMap = JSONObject.parseObject(limitPolicy);

        String order_id = String.valueOf(System.currentTimeMillis());
        Map<String, Object> order = new HashMap<String, Object>();

        if (policyMap!=null&&!policyMap.isEmpty()){
            //3、取出政策里的数量是不是大于redis计数器的数量
            int limitQuanty = Integer.parseInt(policyMap.get("quanty").toString());

            //这里开启计数器，并取名为：SKU_QUANTY_{sku_id}
            if (stringRedisTemplate.opsForValue().increment("SKU_QUANTY_"+sku_id)<=limitQuanty){
                //4、写入订单队列
                // tb_order: order_id, total_fee, actual_fee, post_fee, payment_type, user_id, status, create_time
                // tb_order_detail: order_id, sku_id, num, title, own_spec, price, image, create_time
                // tb_sku: sku_id, title, images, stock, price, indexes, own_spec
                String sku = stringRedisTemplate.opsForValue().get("SKU_"+sku_id);
                Map<String, Object> skuMap = JSONObject.parseObject(sku);

                order.put("order_id", order_id);
                order.put("total_fee", skuMap.get("price"));
                order.put("actual_fee", policyMap.get("price"));
                order.put("post_fee", 0);
                order.put("payment_type", 0);
                order.put("user_id", orderInfo.get("user_id"));
                order.put("status", 1);

                String now = restTemplate.getForObject("http://leyou-time-server/getTime", String.class);
                order.put("create_time", now);

                order.put("sku_id", sku_id);
                order.put("num", 1);
                order.put("title", skuMap.get("title"));
                order.put("own_spec", skuMap.get("own_spec"));
                order.put("price", policyMap.get("price"));
                order.put("image", skuMap.get("images"));

                String orderObj = JSON.toJSONString(order);

                amqpTemplate.convertAndSend("order_queue", orderObj);

            }else {
                //5、如果取出政策里的数量不大于redis计数器的数量，提示：商品已经售完
                resultMap.put("result", false);
                resultMap.put("msg", "商品已经售完！");
                return resultMap;
            }
        }else {
            //6、如果商品不在政策里，提示：活动已经结束
            resultMap.put("result", false);
            resultMap.put("msg", "活动已经结束！");
            return resultMap;
        }

        //7、返回正常消息
        resultMap.put("order_id", order_id);
        resultMap.put("result", true);
        resultMap.put("msg", "");
        return resultMap;
    }
}
